﻿using Hvam.SharePoint.Search.Query.Site.Models;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Hvam.SharePoint.Search.Query.Site.ResultSteps
{
    internal class UrlResultStep : SiteSearchResultStep
    {
        public UrlResultStep(SiteSearchQuery query) : base(query)
        {
            
        }

        public override SiteSearchResult Process(SiteSearchResult result)
        {
            if (Query.RequestedProperties.Contains("path"))
            {
                if (!result.Properties.ContainsKey("url"))
                {
                    var item = result.ListItem;

                    var web = item.Web;

                    if (item.File != null)
                    {
                        result.Properties.Add("url", web.Url.TrimEnd('/') + "/" + item.File.Url);
                    }
                    else
                    {
                        var display = item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM];
                        
                        if (item.ID == 0 && item.ParentList.HasExternalDataSource)
                        {
                            result.Properties.Add("url", web.Url.TrimEnd('/') + "/" + display.Url + "?ID=" + item["BdcIdentity"]);
                        }
                        else
                        {
                            result.Properties.Add("url", web.Url.TrimEnd('/') + "/" + display.Url + "?ID=" + item.ID);
                        }
                    }
                }

                if (result.Properties.ContainsKey("url") && !result.Properties.ContainsKey("urlEncoded"))
                {
                    result.Properties.Add("urlEncoded", SPEncode.UrlEncode(result.Properties["url"]));
                }
            }
            return result;
        }
    }
}
